package com.xsd.juc;

/**
 * @Description: 阻塞队列
 * @Author: zhoufuzong
 * @Created: 2021-01-02 19:24:21
 * @Version: 1.1.0
 */

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * 1 两个数据结构： 栈/ 队列
 * 1.1 栈    后进后出
 * 1.2 队列   先进先出
 * 1.3 总结
 *
 * 2  阻塞队列
 *      2.1 阻塞     必须要阻塞/ 不得不阻塞
*
 *   3  how
 */

public class BlockingQueueDemo {

    public static void main(String[] args) throws InterruptedException {

        BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(3);

//        System.out.println(blockingQueue.add("a"));
//        System.out.println(blockingQueue.add("b"));
//        System.out.println(blockingQueue.add("c"));


//        System.out.println(blockingQueue.add("x")); // 抛出异常
//        System.out.println(blockingQueue.remove());
////        System.out.println(blockingQueue.remove());
////        System.out.println(blockingQueue.remove());
////        System.out.println(blockingQueue.remove());    // 抛异常
//        System.out.println(blockingQueue.element());  // 检查队首元素  a


//        System.out.println(blockingQueue.offer("a"));
//        System.out.println(blockingQueue.offer("b"));
//        System.out.println(blockingQueue.offer("c"));
//        System.out.println(blockingQueue.offer("x"));  // 插入数据 队列满时 返回false

//        System.out.println(blockingQueue.poll());
//        System.out.println(blockingQueue.poll());
//        System.out.println(blockingQueue.poll());
//        System.out.println(blockingQueue.poll());   // null

//        blockingQueue.put("a");
//        blockingQueue.put("a");
//        blockingQueue.put("a");
//        blockingQueue.put("a");  // 一直阻塞，等待，因为队列长度满了


//        System.out.println(blockingQueue.take());
//        System.out.println(blockingQueue.take());
//        System.out.println(blockingQueue.take());
//        System.out.println(blockingQueue.take());  // 一直阻塞，直到有了，取出来，然后才结束



        System.out.println(blockingQueue.offer("b"));
        System.out.println(blockingQueue.offer("b"));
        System.out.println(blockingQueue.offer("b"));
        System.out.println(blockingQueue.offer("a", 3L, TimeUnit.SECONDS));  // 等待3秒，仍然没有，打印fasle 过时不候

    }
}
